//
//  KLMConnectManager.swift
//  KLM
//
//  Created by 朱雨 on 2022/4/8.
//

import Foundation
import nRFMeshProvision
import CoreBluetooth

class KLMConnectManager {
    
    //蓝牙连接状态
    var state: CBManagerState?
    
    var success: (() -> Void)?
    var failure: (() -> Void)?
    
    func connectToNode(node: Node, success: @escaping () -> Void, failure: @escaping () -> Void) {
        
        KLMSmartNode.sharedInstacnce.delegate = self
        
        self.success = success
        self.failure = failure
        
        if MeshNetworkManager.bearer.isOpen {
            startConnect(node: node)
        } else {
            if KLMMesh.instacnce.onLineNodes.contains(node.nodeuuidString) { ///在线，但是直连设备还没连上,延长2秒给APP连接直连设备
                DispatchQueue.main.asyncAfter(deadline: 3) {
                    self.startConnect(node: node)
                }
            } else {
                self.startConnect(node: node)
            }
        }
    }
    
    private func startConnect(node: Node) {
        
        let parame = parameModel(dp: .power)
        KLMSmartNode.sharedInstacnce.readMessage(parame, toNode: node)
    }
    
    func connectToGroup(group: Group, success: @escaping () -> Void, failure: @escaping () -> Void) {
        
        self.success = success
        self.failure = failure
    
        KLMSmartGroup.sharedInstacnce.readMessage(toGroup: group) {source in
            SVProgressHUD.dismiss()
            self.onSuccess()
        } failure: { error in
            KLMShowError(error)
            self.onFailure()
        }
    }
    
    func connectToAllNodes(success: @escaping () -> Void, failure: @escaping () -> Void) {
        
        self.success = success
        self.failure = failure
        
        if KLMSmartGroup.allNodes().count == 0 {
            let err = MessageError()
            err.message = KLMLocalizable.LANGLOC("No devices")
            KLMShowError(err)
            self.onFailure()
            return
        }
        
//        if KLMRemoteManager.shared.isRemote {
//            self.onSuccess()
//            return
//        }
        
        //一个设备都没连接,群组发送消息也可以发送出去，没报异常。所以要添加这个
        if !MeshNetworkManager.bearer.isOpen {
            let err = MessageError()
            err.message = KLMLocalizable.LANGLOC("Make sure the device is powered on and near your device.")
            KLMShowError(err)
            self.onFailure()
            return
        }
    
        self.onSuccess()
    }
    
    private func onSuccess() {
        
        self.success?()
        self.success = nil
        self.failure = nil
    }
    
    private func onFailure() {
        
        self.failure?()
        self.failure = nil
        self.success = nil
    }
    
    //单例
    static let shared = KLMConnectManager()
    private init(){}
}

extension KLMConnectManager {
    
    ///检查手机蓝牙状态
    static func checkBluetoothState() throws {
        
        let err = MessageError()
        switch KLMConnectManager.shared.state {
        case .poweredOff:
            ///弹出手机蓝牙提示框
            err.message = KLMLocalizable.LANGLOC("Please turn on the Bluetooth of your mobile phone")
            throw err
        case .unauthorized:
            ///弹出APP蓝牙授权提示
            err.message = KLMLocalizable.LANGLOC("The application is not authorized to use the Bluetooth")
            throw err
        default:
            break
        }
    }
}

extension KLMConnectManager: KLMSmartNodeDelegate {
    
    func smartNode(_ manager: KLMSmartNode, didReceiveVendorMessage message: responsParame?) {
        
        if message?.dp == .power {
            self.onSuccess()
            
        }
    }
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?) {
        
        KLMShowError(error)
        self.onFailure()
    }
}
